/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package amfservices.navigate;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author KieuAnh
 */
public class SessionCache
{
    private static final SessionCache inst = new SessionCache();
    
    public static SessionCache inst()
    {
        return inst;
    }
    private static final long EXPIRE_TIME = 30;
    private final Cache<String, String> cache;
    private final Map<String, String> uidToSession = new ConcurrentHashMap();
    
    private SessionCache()
    {
        cache = CacheBuilder.newBuilder()
                .expireAfterAccess(EXPIRE_TIME, TimeUnit.MINUTES)
                .removalListener(new OnSessionExpired(this))
                .build();
    }
    
    public String getUID(String session)
    {
        return cache.getIfPresent(session);
    }
    
    public boolean isValid(String session)
    {
        return cache.getIfPresent(session) != null;
    }
    
    public void putSession(String session, String uid)
    {
        cache.put(session, uid);
        uidToSession.put(uid, session);
    }
    
    public String tryGetSession(String uid)
    {
        return uidToSession.get(uid);
    }
    
    private static class OnSessionExpired implements RemovalListener<String, String>
    {
        private final SessionCache cache;

        public OnSessionExpired(SessionCache cache) {
            this.cache = cache;
        }
        
        @Override
        public void onRemoval(RemovalNotification<String, String> rn) {
            try
            {
                cache.uidToSession.remove(rn.getValue());
            }
            catch (Exception ex)
            {
                
            }
        }
    }
}